#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/socket.h>
#define BUF_SIZE 100
#define MAX(a, b) ((a) > (b) ? (a) : (b))
void error_handling(char* message);

int main(int argc, char* argv[])
{
    //socket相关
    int serv_sock, clnt_sock;
    struct sockaddr_in serv_adr, clnt_adr;
    socklen_t adr_sz;

    //select相关
    struct timeval timeout;//超时
    fd_set reads, cpy_reads;//fd_set
    int fd_max, fd_num;//监视范围

    //buf相关
    int str_len, i;
    char buf[BUF_SIZE];

    if(argc != 2)
    {
        printf("Usage : %s <port> \n", argv[0]);
        exit(1);
    }

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_adr.sin_port = htons(atoi(argv[1]));

    if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))== -1)
        error_handling("bind() error\n");

    if(listen(serv_sock, 5) == -1)
        error_handling("listen() error\n");

    FD_ZERO(&reads);//将fd_set变量中所有位初始化为0
    FD_SET(serv_sock, &reads);//在fd_set变量中注册文件描述符fd的信息
    fd_max = serv_sock;

    while(1)
    {
        cpy_reads = reads;//为了记住初始值，select的通用方法
        timeout.tv_sec = 5;//调用select函数前每次都要初始化timeval结构体变量
        timeout.tv_usec = 5000;//每次调用select函数timeval成员都会被替换成超时前剩余时间

        if((fd_num = select(fd_max + 1, &cpy_reads, 0, 0, &timeout)) == -1)//select失败
            break;
        if(fd_num == 0)//超时
            continue;
        for(i = 0; i < fd_max + 1; i++)
        {
            if(FD_ISSET(i, &cpy_reads))//查找发生变化的套接字
            {
                if(i == serv_sock)//如果是服务器端，说明有新的连接请求
                {
                    adr_sz = sizeof(clnt_adr);
                    clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz);
                    FD_SET(clnt_sock, &reads);
                    fd_max = MAX(fd_max, clnt_sock);
                    printf("connected client : %d \n", clnt_sock);
                }
                else//否则是连接客户端的套接字，提供服务
                {
                    str_len = read(i, buf, BUF_SIZE);
                    if(str_len == 0)//结束连接
                    {
                        FD_CLR(i, &reads);
                        close(i);
                        printf("closed client : %d \n", i);
                    }
                    else//回声
                        write(i, buf, str_len);
                }
            }
        }
    }
    close(serv_sock);
    return 0;
}

void error_handling(char* message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(-1);
}

